package cn.niit.pm.controller;

import cn.niit.pm.entity.Department;
import cn.niit.pm.entity.Employee;
import cn.niit.pm.service.DepartmentService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** fahui
 * 部门信息的Controller
 * */

@Slf4j
@Api(value = "测试接口", tags = "部门管理相关的接口")
@Controller
@RequestMapping("/department_infor")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService; //用于调用service接口

    /*
     * (点击左侧栏目后的请求——最后渲染员工信息页面)
     * */
    @GetMapping("/department_infor")
    public String departmentinnforIndex(Department department, Model model){
        List<Department> departmentList = departmentService.selectListByDepartment(department);
        model.addAttribute("departmentList",departmentList);
        return "department_infor/department_infor";
    }
    /*
     * 点击“添加或修改”按钮 发送get请求——跳转到员工添加或修改页面(并且初始化页面)
     * */
    @GetMapping("/{id}")
    public  String intoAdd(Model model, @PathVariable("id") Integer departmentId){
        Department department = null;
        if (null != departmentId && departmentId > 0){
            department = departmentService.selectByDepartmentId(departmentId);
        }else {
            department = new Department();
        }
        model.addAttribute("department",department);
        return "department_infor/add_department";
    }
    /*
     * 添加内容填写完毕后 点击“保存”发送post请求
     * */
    @PostMapping("")
    public String addDepartment(Model model, @Validated Department department, Employee employee, BindingResult result, HttpServletRequest request){
        log.info("待添加的用户信息：{}", department);
        if(result.hasErrors()){
            Map<String, String> errMap = new HashMap<>();
            for(FieldError error : result.getFieldErrors()){
                log.warn("参数校验异常：{} ，提示信息： {} ", error.getField(), error.getDefaultMessage());
                errMap.put(error.getField(), error.getDefaultMessage());
            }
            model.addAttribute("errors", errMap);
            model.addAttribute("department", department);
            return "department_infor/add_department";
        }
        Employee loginEmployee = (Employee) request.getSession().getAttribute("employee");
        department.setCreateUserId(loginEmployee.getEmployeeId());
        department.setCreateUserName(loginEmployee.getEmployeeName());
        department.setGmtCreate(new Date());
        int rows = departmentService.insertDepartment(department);
        return "redirect:/department_infor/department_infor";
    }


    /**
     * 更新内容完毕后，点击“保存”按钮，发送put请求
     */
    @PutMapping("")
    public String updateEmployee(Employee employee, Department department, HttpServletRequest request){
        Employee loginEmployee = (Employee) request.getSession().getAttribute("employee");
        log.info("待更新的用户：{}", department);
        //为修改的记录赋值更新人信息
        department.setModifyUserId(loginEmployee.getEmployeeId());
        department.setModifyUserName(loginEmployee.getEmployeeName());
        department.setGmtModified(new Date());
        int rows = departmentService.updateDepartment(department);
        log.info("被更新的记录数：{}", rows);
        if(rows <= 0){
            return "/add_department";
        }
        return "redirect:/department_infor/department_infor";
    }


    /**
     * 删除用户
     * @param departmentId
     * @return
     */
    @ResponseBody
    @DeleteMapping("/{id}")
    public String deletEmployee(@PathVariable("id")  Integer departmentId){
        System.out.println(departmentId);
        int rows = 0;
        if(null != departmentId){
            rows = departmentService.deleteByDepartmentId(departmentId);
            if(rows > 0){
                return "true";
            }
        }
        return "false";
    }

}
